const canvas1 = document.getElementById('canvas1');
const canvas2 = document.getElementById('canvas2');
const diffCanvas = document.getElementById('diffCanvas');
const ctx1 = canvas1.getContext('2d');
const ctx2 = canvas2.getContext('2d');
const diffCtx = diffCanvas.getContext('2d');

let image1Loaded = false;
let image2Loaded = false;

function loadImage(file, canvas, ctx, isFirstImage) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(e) {
            const img = new Image();
            img.onload = function() {
                canvas.width = img.width;
                canvas.height = img.height;
                
                ctx.imageSmoothingEnabled = true;
                ctx.imageSmoothingQuality = 'high';
                
                ctx.drawImage(img, 0, 0);
                
                if (isFirstImage) {
                    image1Loaded = true;
                } else {
                    image2Loaded = true;
                }
                resolve();
                if (image1Loaded && image2Loaded) {
                    compareImages();
                }
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('image1').addEventListener('change', function(e) {
    if (e.target.files[0]) {
        debugInfo.innerHTML = '';
        image1Loaded = false;
        image2Loaded = false;
        loadImage(e.target.files[0], canvas1, ctx1, true)
            .then(() => log('图片1加载成功'))
            .catch(err => log('图片1加载失败: ' + err));
    }
});

document.getElementById('image2').addEventListener('change', function(e) {
    if (e.target.files[0]) {
        debugInfo.innerHTML = '';
        image2Loaded = false;
        loadImage(e.target.files[0], canvas2, ctx2, false)
            .then(() => log('图片2加载成功'))
            .catch(err => log('图片2加载失败: ' + err));
    }
}); 